const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')

const index = require('./routes/index')
const users = require('./routes/users')

// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))
global.user = [
  {
    id: "5e4915df-efda-49f2-a141-d96948cd78b0",
    username: "18011111111",
    password: "123123",
    nickname: "张三",
    avatar: "https://ts3.cn.mm.bing.net/th?id=OIP-C.y6rdSCGpxbfeb8Rd1CpSuwAAAA&w=250&h=250&c=8&rs=1&qlt=90&o=6&dpr=1.3&pid=3.1&rm=2"
  },
  {
    id: "c6067c16-e31e-4573-85dc-91bbbb5a6506",
    username: "18022222222",
    password: "123123",
    nickname: "李四",
    avatar: "https://ts4.cn.mm.bing.net/th?id=OIP-C.H9x1BxITI75Tc3IMOKJekwAAAA&w=250&h=249&c=8&rs=1&qlt=90&o=6&dpr=1.3&pid=3.1&rm=2"
  }
]
// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
